//
//  ClubLoginViewController.swift
//  77Club
//
//  Created by Apple on 2024/8/29.
//

import UIKit

class ClubLoginViewController: ClubBaseViewController, UITextFieldDelegate {

    private let bgView = c_make_ex(UIImageView.self)
        .image("Login_bg").mode(.scaleAspectFill).end()
    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let logoImageView = c_make_ex(UIImageView.self)
        .image("Login_logo").mode(.scaleAspectFill).end()
    private let titleLabel = c_make_ex(UILabel.self)
        .text("欢迎来到乐玩").color("#17181A").font(24.font_semiBold).end()
    private let codeLoginButton = c_make_ex(UIButton.self)
        .text("验证码登录").font(18.font_semiBold).color("#47494D")
        .color("#2E3033", state: .selected).end()
    private let passwordButton = c_make_ex(UIButton.self)
        .text("密码登录").font(18.font_medium).color("#47494D")
        .color("#2E3033", state: .selected).end()
    private let codeLineView = c_make_ex(UIView.self)
        .bgColor("#FF831A").corner(4).end()
    private let passwordLineView = c_make_ex(UIView.self)
        .bgColor("#FF831A").corner(4).end()
    private let checkButton = c_make_ex(UIButton.self)
        .image("Login_checkNor").image("Login_checkSel", state: .selected).end()
    private let loginButton = c_make_ex(UIButton.self)
        .bgImage(UIImage.colorToImage(color: "#FFC99A".toColor), state: .disabled)
        .bgImage(UIImage.colorToImage(color: "#FF831A".toColor))
        .corner(22).color(.white).text("登 录").end()
    
    private let bottomLabel = c_make_ex(UILabel.self)
        .text("若没有账号，手机号验证码登陆即注册").color("#7B7D80")
        .alignment(.center).font(13.font_regular).end()
    private lazy var activeLabel    = ActiveLabel()
    private var setupButton = UIIconButton(style: .trailing(itemSpace: 3))
    
    private let passwordView = ClubPasswordLoginView()
    private let codeView = ClubCodeLoginView()
    
    private var type = 1 //1.验证码登录 2.密码登录
    
    private var sessionid = "" //收到的验证码
    private var panduanStr = "1" // 1 代表已经注册 0 代表没有
    
    var fromMineVC = false
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        self.passwordView.updateLoginButtonState()
        // 禁用侧滑手势的代理
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        // 恢复默认代理
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            bgView
            backButton
            titleLabel
            logoImageView
            codeLineView
            passwordLineView
            codeLoginButton
            passwordButton
            loginButton
            checkButton
            activeLabel
            setupButton
            bottomLabel
            passwordView
            codeView
        }
        
        bgView.fillContainer()
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        titleLabel.leading(16).top(.navi_height + 40)
        logoImageView.trailing(0).top(.statusHeight + 4).height(187).width(142)
        codeLoginButton.leading(16).top(.navi_height + 104).width(90).height(20)
        codeLineView.height(8).width(65).top(.navi_height + 118)
        codeLineView.CenterX == codeLoginButton.CenterX
        passwordButton.leading(138).top(.navi_height + 104).width(72).height(20)
        passwordLineView.height(8).width(65).top(.navi_height + 118)
        passwordLineView.CenterX == passwordButton.CenterX
        codeView.leading(0).trailing(0).height(124)
        codeView.Top == codeLineView.Bottom + 40
        passwordView.leading(0).trailing(0)
        passwordView.Top == codeLineView.Bottom + 40
        loginButton.leading(16).trailing(16).height(44)
        loginButton.Top == codeView.Bottom + 66
        checkButton.leading(20).size(14)
        checkButton.Top == loginButton.Bottom + 16
        activeLabel.leading(38).height(20)
        activeLabel.CenterY == checkButton.CenterY
        setupButton.leading(60).trailing(60).height(20)
        setupButton.Top == activeLabel.Bottom + 125
        bottomLabel.leading(15).trailing(15)
        bottomLabel.Top == setupButton.Bottom + 12
                
        codeLoginButton.isSelected = true
        codeLineView.isHidden = false        
        passwordButton.isSelected = false
        passwordLineView.isHidden = true
        codeView.isHidden = false
        passwordView.isHidden = true
        
        configActiveStyle()
        
        setupButton.style { v in
            v.iconSize = CGSize(width: 17, height: 16)
            v.setImage("Login_go".toImage, for: .normal)
            v.setTitle("去注册", for: .normal)
            v.setTitleColor("#FF8319".toColor, for: .normal)
            v.titleLabel?.font = 16.font_regular
            v.addTarget(self, action: #selector(clickSetupButton), for: .touchUpInside)
            v.isHidden = true
        }
        
        loginButton.isEnabled = false
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        codeLoginButton.addTarget(self, action: #selector(clickCodeButton), for: .touchUpInside)
        passwordButton.addTarget(self, action: #selector(clickPasswordButton), for: .touchUpInside)
        checkButton.addTarget(self, action: #selector(clickCheckButton), for: .touchUpInside)
        loginButton.addTarget(self, action: #selector(clickLoginButton), for: .touchUpInside)
        
        codeView.updateViewLayout = { isShow in
 
            if isShow {
                self.codeView.heightConstraint?.constant = 272
                self.setupButton.topConstraint?.constant = 50
            }else{
                self.codeView.heightConstraint?.constant = 142
                self.setupButton.topConstraint?.constant = 125
            }
        }
        passwordView.forgetBlock = {
            self.navigationController?.pushViewController(ClubLoginVerfityViewController(), animated: true)
        }
        passwordView.updateStateBlock = { enable in
            self.loginButton.isEnabled = enable
        }
        codeView.updateStateBlock = { enable in
            self.loginButton.isEnabled = enable
        }
    }
    
    private func configActiveStyle() {
        let customType = ActiveType.custom(pattern: "《乐玩用户协议》")
        let customType1 = ActiveType.custom(pattern: "《隐私政策》")
        activeLabel.isShowUnderLine = false
        activeLabel.font = 12.font_medium
        activeLabel.numberOfLines = 0
        activeLabel.textAlignment = .left
        activeLabel.enabledTypes = [customType, customType1]
        activeLabel.text = "同意《乐玩用户协议》和《隐私政策》"
        activeLabel.textColor = "#323233".toColor
        activeLabel.customColor[customType] = "#FF8319".toColor
        activeLabel.customColor[customType1] = "#FF8319".toColor
        
        activeLabel.handleCustomTap(for: customType) { [weak self] str in
            let urlString = RaeRequestParameterConfig.shared.baseUrlStr + "ct=zhanwu&ac=agreement&id=1&language=0"
            let webView = ClubWebViewController()
            webView.urlString = urlString
            webView.titleName = "用户协议"
            self?.navigationController?.pushViewController(webView, animated: true)
        }
        activeLabel.handleCustomTap(for: customType1) { [weak self] str in
            let urlString = RaeRequestParameterConfig.shared.baseUrlStr + "ct=zhanwu&ac=agreement&id=2&language=0"
            let webView = ClubWebViewController()
            webView.urlString = urlString
            webView.titleName = "隐私协议"
            self?.navigationController?.pushViewController(webView, animated: true)
        }
    }
    
    override func clickBackButton() {
        
        if fromMineVC {
            
            if let navigationController = self.navigationController {
                // 假设你想要跳转到的视图控制器是DetailViewController
                var isPop = false
                for viewController in navigationController.viewControllers {
                    if viewController is ClubSquareViewController {
                        isPop = true
                        navigationController.popToViewController(viewController, animated: true)
                        break
                    }else if viewController is ClubMineViewController {
                        isPop = true
                        navigationController.popToViewController(viewController, animated: true)
                        break
                    }
                }
                if !isPop {
                    self.navigationController?.popViewController(animated: true)
                }
            }            
        }else{
            self.navigationController?.popViewController(animated: true)
        }
    }
}


//MARK: action
extension ClubLoginViewController {
    
    @objc private func clickLoginButton(){
        
        if !checkButton.isSelected {
            "请先阅读并且同意用户协议以及隐私协议".toast_error
            return
        }
        if type == 1 {
            
            var inviteCode = ""
            var passwordStr = ""
            guard let phoneNum = codeView.phoneTextfield.text, phoneNum.isValidPhoneNumber else {
                "请输入正确的手机号".toast_error
                return
            }
            
            guard let codeNum = codeView.codeTextfield.text, codeNum.validateCode() else {
                "请输入正确的验证码".toast_error
                return
            }
            
            if codeView.panduanStr == "0" {
                guard let password = codeView.passwordTextfield.text, password.validatePassword() else {
                    "请输入6~12为密码".toast_error
                    return
                }
                passwordStr = password
                if let inviteC = codeView.inviteTextfield.text, inviteC.count > 0 {
                    inviteCode = inviteC
                }
            }
            
            Task{

                let models = await network.request(.phoneNumLogin(phone: phoneNum, sessionid: codeView.sessionid, code: codeNum, passwd: passwordStr, invite: inviteCode), type: ClubLoginModel.self)
                if let model = models.model, models.isSuccess {
                    "登录成功".toast_success
                    DispatchQueue.main.async {
                        NotificationCenter.default.post(name: .reloadWebView, object: nil)
                    }
                    UserDefaultsManager.setString(model.value, forKey: .uid)
                    self.navigationController?.popViewController(animated: true)
                }else{
                    models.errorMessage?.toast_error
                }
            }
            
        } else {
            
            guard let phoneNum = passwordView.phoneTextfield.text, phoneNum.isValidPhoneNumber else {
                "请输入正确的手机号".toast_error
                return
            }
            
            guard let password = passwordView.passwordTextfield.text, password.validatePassword() else {
                "请输入6~12为密码".toast_error
                return
            }
            
            Task{
                let timeStr = String(Date().toTimeStamp())
                let sign = phoneNum + password + timeStr + "riowreopfdwrops21qe"
                let signMd5 = RaeRequestParameterConfig.shared.md5HexDigest(sign)
                let models = await network.request(.login(user_name: phoneNum, passwd: password, t: timeStr, sign: signMd5), type: ClubLoginModel.self)
                if let model = models.model, models.isSuccess {
                    "登录成功".toast_success
                    DispatchQueue.main.async {
                        NotificationCenter.default.post(name: .reloadWebView, object: nil)
                    }
                    UserDefaultsManager.setString(model.value, forKey: .uid)
                    if UserDefaultsManager.getBool(forKey: .isRemember) {
                        UserDefaultsManager.setString(phoneNum, forKey: .phone)
                        UserDefaultsManager.setString(password, forKey: .password)
                    }
                    self.navigationController?.popViewController(animated: true)
                }else{
                    models.errorMessage?.toast_error
                }
            }
        }
    }
    
    @objc private func clickCheckButton(){
        
        checkButton.isSelected = !checkButton.isSelected
    }
    
    @objc private func clickSetupButton(){
        
        self.navigationController?.pushViewController(ClubSetupViewController(), animated: true)
    }
    
    @objc private func clickCodeButton(){
        
        if !codeLoginButton.isSelected {
            
            type = 1
            codeLoginButton.titleLabel?.font = 18.font_semiBold
            passwordButton.titleLabel?.font = 18.font_medium
            
            codeLoginButton.isSelected = true
            codeLineView.isHidden = false
            passwordButton.isSelected = false
            passwordLineView.isHidden = true
            codeView.isHidden = false
            passwordView.isHidden = true
            passwordView.clearInfo()
        }
    }
    
    @objc private func clickPasswordButton(){
        
        if !passwordButton.isSelected {
            
            type = 2
            passwordButton.titleLabel?.font = 18.font_semiBold
            codeLoginButton.titleLabel?.font = 18.font_medium
            
            passwordButton.isSelected = true
            passwordLineView.isHidden = false
            codeLoginButton.isSelected = false
            codeLineView.isHidden = true
            codeView.isHidden = true
            passwordView.isHidden = false
            codeView.clearInfo()
            self.codeView.heightConstraint?.constant = 142
            self.setupButton.topConstraint?.constant = 125
        }
    }
}

